package com.openweixin.sheknows.service.impl;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.openweixin.sheknows.common.Pager;
import com.openweixin.sheknows.dao.AnswerDao;
import com.openweixin.sheknows.dao.QuestionDao;
import com.openweixin.sheknows.dao.UserNewScoreDao;
import com.openweixin.sheknows.domain.Answer;
import com.openweixin.sheknows.domain.Question;
import com.openweixin.sheknows.domain.UserNewScore;
import com.openweixin.sheknows.service.AnswerService;
@Service
public class AnswerServiceImpl extends BaseServiceImpl<Answer, Integer> implements AnswerService { 
	
	@Autowired
	private QuestionDao questionDao;
	@Autowired
	private UserNewScoreDao unsDao;
	
	@Resource
	public void setBaseDao(AnswerDao dao) {
		super.setBaseDao(dao);
	}

	@Override
	public boolean answerByLock(Integer qID, Integer extpertID, Answer answer) {
		Question question= questionDao.get(qID);
		if(question.getLockExpert()!=extpertID || question.getStatus()==2){//不是自己锁定的问题,或此问题已经被解答
			return false;
		}
		answer.setQuestion(question);;
		getBaseDao().save(answer);
		return true;
	}

	@Transactional
	@Override
	public boolean answer(Integer qID, Integer extpertID, Answer answer) {
		Question question= questionDao.get(qID);
		if(question.getStatus()==2)//此问题已经被解答
			return false;
		question.setStatus(1);
		answer.setQuestion(question);;
		getBaseDao().save(answer);
		return true;
	}

	@Override
	public boolean saveScore(Integer aID, Integer uID,Integer score) {
		Answer answer=getBaseDao().load(aID);
		if(answer.getQuestion().getUser().getUid() != uID || answer.getScore()!= null){ //评分人不匹配或已经评分
			return false;
		}
		answer.setScore(score);
		return true;
	}
	
	
	@Override
	public Pager<Answer> findByPager(Pager<Answer> pager) {
		super.findByPager(pager);
		List<Answer> answerList = pager.getList();
		for (Answer answer : answerList) {
			Integer uid = answer.getExpert().getUid();
			Integer qid = answer.getQuestion().getQid();
			UserNewScore uns = unsDao.getNewScoreByUidAndQid(uid, qid);
			answer.setNewScore(uns != null);
		}
		return pager;
	}
	
}
